package com.yupi.yuojbackendjudgeservice.judge.codesandbox.impl;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import com.yupi.yuojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.yupi.yuojbackendmodel.model.codesandbox.ExcuteCodeRequest;
import com.yupi.yuojbackendmodel.model.codesandbox.ExcuteCodeResponse;


public class RemoteCodeSandbox implements CodeSandbox {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExcuteCodeResponse excuteCode(ExcuteCodeRequest excuteCodeRequest) {

        System.out.println("远程代码沙箱");
        String url = "49.235.182.115:8090/executeCode";
        String jsonStr = JSONUtil.toJsonStr(excuteCodeRequest);
        //发送远程的请求  这里应该也可以采用restTemplate
        HttpResponse httpResponse = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(jsonStr)
                .execute();
        String responseStr = httpResponse.body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"远程沙箱错误" + responseStr);
        }
        ExcuteCodeResponse excuteCodeResponse = JSONUtil.toBean(responseStr, ExcuteCodeResponse.class);
        return excuteCodeResponse;
    }
}
